package com.sptus.system.utils;


import com.sptus.common.utils.IPLocationUtils;
import com.sptus.common.vo.ProblemFeedbackVo;
import com.sptus.system.domain.Equipment;
import com.sptus.system.domain.alarm.Alarm;
import com.sptus.system.domain.alarm.Fault;
//import com.sptus.system.domain.alarm.Alarm;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import java.text.SimpleDateFormat;
import java.util.*;

public class GmailSendVerificationCode {

    private static final String WARNING_TEMPLATE = "<!DOCTYPE html>\n" +
            "<html lang=\"en\">\n" +
            "<head>\n" +
            "    <meta charset=\"UTF-8\">\n" +
            "    <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n" +
            "    <title>SPT Verification Code</title>\n" +
            "</head>\n" +
            "<body style=\"margin: 0; padding: 20px; background-color: #F5F5F5; font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;\">\n" +
            "    <div style=\"max-width: 600px; margin: 0 auto; padding: 40px; background: #FFFFFF; border-radius: 24px; box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);\">\n" +
            "        <!-- Logo -->\n" +
            "        <div style=\"margin-left: -10px; margin-bottom: 24px;\">\n" +
            "            <img src=\"https://cloud.sptus.com/app/app-logo.png\" alt=\"SPT\" style=\"width: 60px; height: 60px;\">\n" +
            "        </div>\n" +
            "\n" +
            "        <!-- Title -->\n" +
            "        <h1 style=\"font-size: 20px; font-weight: 600; color: #000000; margin: 0 0 16px 0;\">\n" +
            "           SPT Device Warning LOG\n" +
            "        </h1>\n" +
            "\n" +
            "        <!-- Description -->\n" +
            "        <p style=\"font-size: 14px; color: #666666; margin: 0 0 24px 0;\">\n" +
            "           This is the content of the iot process log\n" +
            "        </p>\n" +
            "\n" +
            "        <!-- Information -->\n" +
            "        <div style=\"font-size: 14px; font-weight: 600; color: #000000; margin: 0 0 24px 0; letter-spacing: 1px;\">\n" +
            "            SN:123456SN,MSGTYPE:123456MSG\n" +
            "        </div>\n" +
            "\t\t<div style=\"font-size: 14px; font-weight: 600; color: #000000; margin: 0 0 24px 0; letter-spacing: 1px;\">\n" +
            "            123456CONTENT\n" +
            "        </div>\n" +
            "        <!-- Time Notice -->\n" +
            "        <h1 style=\"font-size: 16px; font-weight: 60; color: #000000; margin: 0 0 24px 0;\">\n" +
            "          Please go and handle the warning of this device\n" +
            "        </h1>\n" +
            "\n" +
            "        <!-- Company Name -->\n" +
            "        <div style=\"margin-top: 24px;\">\n" +
            "            <p style=\"font-size: 14px; color: #000000; margin: 0;\">SPT</p>\n" +
            "        </div>\n" +
            "    </div>\n" +
            "</body>\n" +
            "</html>";

    private static final String EMAIL_TEMPLATE ="<!DOCTYPE html>\n" +
            "<html lang=\"en\">\n" +
            "<head>\n" +
            "    <meta charset=\"UTF-8\">\n" +
            "    <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n" +
            "    <title>SPT Verification Code</title>\n" +
            "</head>\n" +
            "<body style=\"margin: 0; padding: 20px; background-color: #F5F5F5; font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;\">\n" +
            "    <div style=\"max-width: 600px; margin: 0 auto; padding: 40px; background: #FFFFFF; border-radius: 24px; box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);\">\n" +
            "        <!-- Logo -->\n" +
            "        <div style=\"margin-left: -10px; margin-bottom: 24px;\">\n" +
            "            <img src=\"[LOGO_URL]\" alt=\"SPT\" style=\"width: 60px; height: 60px;\">\n" +
            "        </div>\n" +
            "\n" +
            "        <!-- Title -->\n" +
            "        <h1 style=\"font-size: 20px; font-weight: 600; color: #000000; margin: 0 0 16px 0;\">\n" +
            "            The following is your SPT verification code.\n" +
            "        </h1>\n" +
            "\n" +
            "        <!-- Description -->\n" +
            "        <p style=\"font-size: 14px; color: #666666; margin: 0 0 24px 0;\">\n" +
            "            Use this code to verify your SPT registration attempt.\n" +
            "        </p>\n" +
            "\n" +
            "        <!-- Verification Code -->\n" +
            "        <div style=\"font-size: 32px; font-weight: 600; color: #000000; margin: 0 0 24px 0; letter-spacing: 1px;\">\n" +
            "            123456\n" +
            "        </div>\n" +
            "\n" +
            "        <!-- Time Notice -->\n" +
            "        <h1 style=\"font-size: 16px; font-weight: 600; color: #000000; margin: 0 0 24px 0;\">\n" +
            "            The code will remain valid for the next 10 minutes\n" +
            "        </h1>\n" +
            "\n" +
            "        <!-- Footer Info -->\n" +
            "        <div style=\"font-size: 12px; color: #666666; line-height: 1.5;\">\n" +
            "            <p style=\"margin: 0;\">Requested From: The SPT APP</p>\n" +
            "            <p style=\"margin: 4px 0;\">[Location]</p>\n" +
            "            <p style=\"margin: 4px 0;\">IP: [IP]</p>\n" +
            "        </div>\n" +
            "\n" +
            "        <!-- Company Name -->\n" +
            "        <div style=\"margin-top: 24px;\">\n" +
            "            <p style=\"font-size: 14px; color: #000000; margin: 0;\">SPT</p>\n" +
            "        </div>\n" +
            "    </div>\n" +
            "</body>\n" +
            "</html>";
    private static final String EMAIL_DATA_ALARM ="<!DOCTYPE html>\n" +
            "<html lang=\"en\">\n" +
            "<head>\n" +
            "    <meta charset=\"UTF-8\">\n" +
            "    <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n" +
            "    <title>SPT Verification Code</title>\n" +
            "</head>\n" +
            "<body style=\"margin: 0; padding: 20px; background-color: #F5F5F5; font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;\">\n" +
            "    <div style=\"max-width: 600px; margin: 0 auto; padding: 40px; background: #FFFFFF; border-radius: 24px; box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);\">\n" +
            "        <!-- Logo -->\n" +
            "        <div style=\"margin-left: -10px; margin-bottom: 24px;\">\n" +
            "            <img src=\"[LOGO_URL]\" alt=\"SPT\" style=\"width: 60px; height: 60px;\">\n" +
            "        </div>\n" +
            "\n" +
            "        <!-- Title -->\n" +
            "        <h1 style=\"font-size: 20px; font-weight: 600; color: #000000; margin: 0 0 16px 0;\">\n" +
            "         alarm level:[level]\n" +
            "        </h1>\n" +
            "\n" +
            "        <!-- Description -->\n" +
            "        <p style=\"font-size: 14px; color: #666666; margin: 0 0 24px 0;\">\n" +
            "           This is the content of the device alarm\n" +
            "        </p>\n" +
            "\n" +
            "        <!-- Verification Code -->\n" +
            "        <div style=\"font-size: 14px; font-weight: 600; color: #000000; margin: 0 0 24px 0; letter-spacing: 1px;\">\n" +
            "            123456\n" +
            "        </div>\n" +
            "\n" +
            "        <!-- Time Notice -->\n" +
            "        <h1 style=\"font-size: 16px; font-weight: 60; color: #000000; margin: 0 0 24px 0;\">\n" +
            "          Please go and handle the alarm of this device immediately\n" +
            "        </h1>\n" +
            "\n" +
            "        <!-- Footer Info -->\n" +
            "        <div style=\"font-size: 12px; color: #666666; line-height: 1.5;\">\n" +
            "            <p style=\"margin: 0;\">Requested From: The SPT IotServer</p>\n" +
            "            <p style=\"margin: 4px 0;\">Contacts: [contacts]</p>\n" +
            "            <p style=\"margin: 4px 0;\">Phone:[phone]</p>\n" +
            "            <p style=\"margin: 4px 0;\">Location:[Location]</p>\n" +
            "            <p style=\"margin: 4px 0;\">Date:[Date]</p>\n" +
            "        </div>\n" +
            "\n" +
            "        <!-- Company Name -->\n" +
            "        <div style=\"margin-top: 24px;\">\n" +
            "            <p style=\"font-size: 14px; color: #000000; margin: 0;\">SPT</p>\n" +
            "        </div>\n" +
            "    </div>\n" +
            "</body>\n" +
            "</html>";
    public static void sendEmailWithVerificationCode(String to, String  verificationCode, String from, String smtpHost,
                                                     String smtpPort, String username, String password,String ip) {

        // Gmail SMTP server settings
        String emailSMTPHost = smtpHost;
        String emailSMTPPort = smtpPort;

        final String emailAccount = username;
        final String emailPassword = password;

        Properties props = new Properties();
        props.put("mail.smtp.host", emailSMTPHost);
        props.put("mail.smtp.port", emailSMTPPort);
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.starttls.enable", "true"); // TLS
        props.put("mail.smtp.ssl.protocols", "TLSv1.2");

        // Get the Session object.
        Session session = Session.getInstance(props,
                new Authenticator() {
                    protected PasswordAuthentication getPasswordAuthentication() {
                        return new PasswordAuthentication(emailAccount, emailPassword);
                    }
                });

        try {

            // Create a default MimeMessage object.
            MimeMessage message = new MimeMessage(session);

            // Set From: header field
            message.setFrom(new InternetAddress(from));

            // Set To: header field
            message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));

            // Set Subject: header field
            message.setSubject("Verification Code");

            // Now set the actual message
            String emailBody = "Your verification code is: " + verificationCode;
//            message.setText(emailBody);

            message.setSubject("SPT Verification Code");
            String locationByIP = IPLocationUtils.getLocationByIP(ip);
            String htmlContent = EMAIL_TEMPLATE
                    .replace("123456", verificationCode)
                    .replace("[LOGO_URL]", "https://cloud.sptus.com/app/app-logo.png")
                    .replace("[IP]", ip)
                    .replace("[Location]", locationByIP);

            // 设置邮件内容
            MimeBodyPart htmlPart = new MimeBodyPart();
            htmlPart.setContent(htmlContent, "text/html; charset=utf-8");

            Multipart multipart = new MimeMultipart();
            multipart.addBodyPart(htmlPart);
            message.setContent(multipart);

            // Send message
            Transport.send(message);
            System.out.println("Sent message successfully....");
        } catch (MessagingException mex) {
            mex.printStackTrace();
        }
    }
    public static void sendEmailWithVerificationCode(String to,String account, String type,String  verificationCode, String from, String smtpHost,
                                                     String smtpPort, String username, String password) {

        // Gmail SMTP server settings
        String emailSMTPHost = smtpHost;
        String emailSMTPPort = smtpPort;

        final String emailAccount = username;
        final String emailPassword = password;

        Properties props = new Properties();
        props.put("mail.smtp.host", emailSMTPHost);
        props.put("mail.smtp.port", emailSMTPPort);
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.starttls.enable", "true"); // TLS
        props.put("mail.smtp.ssl.protocols", "TLSv1.2");
        // Get the Session object.
        Session session = Session.getInstance(props,
                new javax.mail.Authenticator() {
                    protected PasswordAuthentication getPasswordAuthentication() {
                        return new PasswordAuthentication(emailAccount, emailPassword);
                    }
                });

        try {
            // Create a default MimeMessage object.
            MimeMessage message = new MimeMessage(session);

            // Set From: header field
            message.setFrom(new InternetAddress(from));

            // Set To: header field
            message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
            HashMap<String, String> stringStringHashMap = setEmailBody(type, account);
            // 示例IP：Google DNS


//            String sub="";
//            String
            // Set Subject: header field
            message.setSubject(stringStringHashMap.get("sub"));
            // Now set the actual message
            String emailBody = stringStringHashMap.get("body") + verificationCode;
            message.setText(emailBody);
            // Send message
            Transport.send(message);
            System.out.println("Sent message successfully....");
        } catch (MessagingException mex) {
            mex.printStackTrace();
        }
    }


   public static HashMap<String,String> setEmailBody(String type, String email){

        HashMap<String, String> stringStringHashMap = new HashMap<>();
       stringStringHashMap.put("sub","Verification Code");
       stringStringHashMap.put("body","Your verification code is: ");
        if (type.equals("Link")){
            stringStringHashMap.put("sub","Application link");
            stringStringHashMap.put("body",email+" application link is: ");
            }
        else  if  (type.equals("Result")){
            stringStringHashMap.put("sub","Application Result");
            stringStringHashMap.put("body","account: "+email+" ");
        }

        return stringStringHashMap;
    }



    public static void sendProblemFeedback(String to, ProblemFeedbackVo problemFeedbackVo, String from, String smtpHost,
                                           String smtpPort, String username, String password) {

        // Gmail SMTP server settings
        String emailSMTPHost = smtpHost;
        String emailSMTPPort = smtpPort;

        final String emailAccount = username;
        final String emailPassword = password;

        Properties props = new Properties();
        props.put("mail.smtp.host", emailSMTPHost);
        props.put("mail.smtp.port", emailSMTPPort);
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.starttls.enable", "true"); // TLS
        props.put("mail.smtp.ssl.protocols", "TLSv1.2");

        // Get the Session object.
        Session session = Session.getInstance(props,
                new javax.mail.Authenticator() {
                    protected PasswordAuthentication getPasswordAuthentication() {
                        return new PasswordAuthentication(emailAccount, emailPassword);
                    }
                });

        try {
            // Create a default MimeMessage object.
            MimeMessage message = new MimeMessage(session);

            // Set From: header field
            message.setFrom(new InternetAddress(from));

            // Set To: header field
            message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));

            // Set Subject: header field
            message.setSubject( "用户:"+problemFeedbackVo.getName()+" 邮箱: "+problemFeedbackVo.getEmail()+"联系方式："+problemFeedbackVo.getContactWay()+"类型:"+( problemFeedbackVo.getMsgType().equals("1")?"问题反馈":"商务沟通") );

            // Now set the actual message
            String emailBody = problemFeedbackVo.getMsg();
            message.setText(emailBody);

            // Send message
            Transport.send(message);
            System.out.println("Sent message successfully....");
        } catch (MessagingException mex) {
            mex.printStackTrace();
        }
    }


//    String to, String  verificationCode, String from, String smtpHost,
//    String smtpPort, String username, String password,String ip
    public static void sendEmailWithAlarm(String to,Equipment equipment, List<Alarm> alarms, String from, String host, String port, String username, String password) {
        // Gmail SMTP server settings
        String emailSMTPHost = host;
        String emailSMTPPort = port;

        final String emailAccount = username;
        final String emailPassword = password;

        Properties props = new Properties();
        props.put("mail.smtp.host", emailSMTPHost);
        props.put("mail.smtp.port", emailSMTPPort);
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.starttls.enable", "true"); // TLS
        props.put("mail.smtp.ssl.protocols", "TLSv1.2");

        // Get the Session object.
        Session session = Session.getInstance(props,
                new Authenticator() {
                    protected PasswordAuthentication getPasswordAuthentication() {
                        return new PasswordAuthentication(emailAccount, emailPassword);
                    }
                });

        try {

            // Create a default MimeMessage object.
            MimeMessage message = new MimeMessage(session);

            // Set From: header field
            message.setFrom(new InternetAddress(from));

            // Set To: header field
            message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));

            // Set Subject: header field
            message.setSubject("SPT Device Alarm： "+equipment.getSn());

            // Now set the actual message
            StringBuilder emailBody = new StringBuilder();
            String level="priority processing";
            for (Alarm alarm : alarms) {
                if(alarm.getGrade()==3){
                    level="High-risk alert";
                }
                emailBody.append(alarm.getDescription()+";<br>\r\n");
            }
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String location = equipment.getLocation();
            String htmlContent = EMAIL_DATA_ALARM
                    .replace("123456",emailBody.toString() )
                    .replace("[LOGO_URL]", "https://cloud.sptus.com/app/app-logo.png")
                    .replace("[contacts]", equipment.getContacts() == null ? "" : equipment.getContacts().toString())
                    .replace("[level]", level)
                    .replace("[Date]", sdf.format(new Date()))
                    .replace("[phone]", equipment.getPhone()==null?"":equipment.getPhone().toString())
                    .replace("[Location]", location==null?"":equipment.getLocation().toString());

            // 设置邮件内容
            MimeBodyPart htmlPart = new MimeBodyPart();
            htmlPart.setContent(htmlContent, "text/html; charset=utf-8");

            Multipart multipart = new MimeMultipart();
            multipart.addBodyPart(htmlPart);
            message.setContent(multipart);

            // Send message
            Transport.send(message);
            System.out.println("Sent message successfully....");
        } catch (MessagingException mex) {
            mex.printStackTrace();
            throw new RuntimeException("sendEmailWithAlarm failed");

        }
    }

    public static void sendEmailWithFault(String reviewers, Equipment equipment, Fault fault, String from, String host, String port, String username, String password) {

        // Gmail SMTP server settings
        String emailSMTPHost = host;
        String emailSMTPPort = port;

        final String emailAccount = username;
        final String emailPassword = password;

        Properties props = new Properties();
        props.put("mail.smtp.host", emailSMTPHost);
        props.put("mail.smtp.port", emailSMTPPort);
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.starttls.enable", "true"); // TLS
        props.put("mail.smtp.ssl.protocols", "TLSv1.2");

        // Get the Session object.
        Session session = Session.getInstance(props,
                new Authenticator() {
                    protected PasswordAuthentication getPasswordAuthentication() {
                        return new PasswordAuthentication(emailAccount, emailPassword);
                    }
                });

        try {

            // Create a default MimeMessage object.
            MimeMessage message = new MimeMessage(session);

            // Set From: header field
            message.setFrom(new InternetAddress(from));

            // Set To: header field
            message.addRecipient(Message.RecipientType.TO, new InternetAddress(reviewers));

            // Set Subject: header field
            message.setSubject("SPT Device Fault： "+equipment.getSn());

            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            // Now set the actual message
            StringBuilder emailBody = new StringBuilder();
            emailBody.append(fault.getEnglish()+";<br>\r\n");
            String level="High-risk alert";
            String location = equipment.getLocation();
            String htmlContent = EMAIL_DATA_ALARM
                    .replace("123456",emailBody.toString() )
                    .replace("[LOGO_URL]", "https://cloud.sptus.com/app/app-logo.png")
                    .replace("[contacts]", equipment.getContacts() == null ? "" : equipment.getContacts().toString())
                    .replace("[level]", level)
                    .replace("[phone]", equipment.getPhone()==null?"":equipment.getPhone().toString())
                    .replace("[Date]", sdf.format(new Date()))
                    .replace("[Location]", location==null?"":equipment.getLocation().toString());


            // 设置邮件内容
            MimeBodyPart htmlPart = new MimeBodyPart();
            htmlPart.setContent(htmlContent, "text/html; charset=utf-8");

            Multipart multipart = new MimeMultipart();
            multipart.addBodyPart(htmlPart);
            message.setContent(multipart);

            // Send message
            Transport.send(message);
            System.out.println("Sent message successfully....");
        } catch (MessagingException mex) {
            mex.printStackTrace();
            throw new RuntimeException("sendEmailWithAlarm failed");

        }
    }

    public static void sendDeviceWarningInfoEmail(String to, String traceId, String sn, String msg, String content, Map<String, String> globalData) {

        String from = globalData.get("spt.auth.code.email"); // 发件人邮箱（你的Gmail）
        String host = globalData.get("spt.auth.code.email.host"); // SMTP服务器地址
        String port = globalData.get("spt.auth.code.email.post"); // Gmail SMTP端口
        // Gmail用户名和密码（或使用应用专用密码）
        String username = globalData.get("spt.auth.code.email.username");
        String password = globalData.get("spt.auth.code.email.pass");

        // Gmail SMTP server settings
        String emailSMTPHost = host;
        String emailSMTPPort = port;

        final String emailAccount = username;
        final String emailPassword = password;

        Properties props = new Properties();
        props.put("mail.smtp.host", emailSMTPHost);
        props.put("mail.smtp.port", emailSMTPPort);
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.starttls.enable", "true"); // TLS
        props.put("mail.smtp.ssl.protocols", "TLSv1.2");

        // Get the Session object.
        Session session = Session.getInstance(props,
                new Authenticator() {
                    protected PasswordAuthentication getPasswordAuthentication() {
                        return new PasswordAuthentication(emailAccount, emailPassword);
                    }
                });
        try {

            // Create a default MimeMessage object.
            MimeMessage message = new MimeMessage(session);

            // Set From: header field
            message.setFrom(new InternetAddress(from));

            // Set To: header field
            message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));

            // Set Subject: header field
            message.setSubject("SPT Device Warning LOG - SN:" + sn + " MSG:" + msg + " " + traceId);
            
            // 构建包含 SN 和 MSG 信息的邮件内容
            String enhancedContent = "设备序列号(SN): " + sn + "\n消息类型(MSG): " + msg + "\n\n原始内容:\n" + content;
            
            String htmlContent = WARNING_TEMPLATE
                    .replace("123456SN", sn)
                    .replace("123456MSG", msg)
                    .replace("123456CONTENT", enhancedContent)
                    .replace("[LOGO_URL]", "https://cloud.sptus.com/app/app-logo.png")
                    ;

            // 设置邮件内容
            MimeBodyPart htmlPart = new MimeBodyPart();
            htmlPart.setContent(htmlContent, "text/html; charset=utf-8");

            Multipart multipart = new MimeMultipart();
            multipart.addBodyPart(htmlPart);
            message.setContent(multipart);

            // Send message
            Transport.send(message);
            System.out.println("Sent message successfully....");
        } catch (MessagingException mex) {
            mex.printStackTrace();
        }
    }
}
